package com.jiyi.widget;


import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;

public class DropEditText extends android.support.v7.widget.AppCompatAutoCompleteTextView implements PopupWindow.OnDismissListener {

    private Drawable mDrawable; // 显示的图
    private PopupWindow mPopupWindow; // 点击图片弹出的popWindow对象
    private ListView mPopListView; // popWindow的布局
    private int mDropDrawableResId; // 下拉图标
    private int mRiseDrawableResID; // 上拉图标
    private String selectedId=""; //选中的ID
    private boolean isShowPop = true;//是否显示提示列表
    public boolean isLoadData = false;//是否数据加载完成
//    public int loadTime = 0;//加载次数，用于失败时判断是否需要重新加载的条件
    private Handler handler;

    public DropEditText(Context context) {
        this(context, null);
    }

    public DropEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DropEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mPopListView = new ListView(context);
        mDropDrawableResId = R.mipmap.icon_drop; // 设置下拉图标
        mRiseDrawableResID = R.mipmap.icon_rise; // 设置上拉图标
        showDropDrawable(); // 默认显示下拉图标
    }

    /**
     * 我们无法直接给EditText设置点击事件，只能通过按下的位置来模拟点击事件
     * 当我们按下的位置在图标包括图标到控件右边的间距范围内均算有效
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                int start = getWidth() - getTotalPaddingRight() ; // 起始位置
                int end = getWidth() -  getPaddingRight(); // 结束位置
                boolean available = (event.getX() > start) && (event.getX() < end);
                if (available) {
                	if (isLoadData) {
                		//只有数据加载完成 点击时才让下拉
                    	showList();
					}
                	else {
						//没加载成功就去重新请求加载
                		handler.sendEmptyMessage(AppConfig.DET_RELOAD);
					}
                	//消费掉此事件
                	return true;
                }
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            mPopupWindow = new PopupWindow(mPopListView, getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE)); // 设置popWindow背景颜色
            mPopupWindow.setFocusable(true); // 让popWindow获取焦点
            mPopupWindow.setOnDismissListener(this);
        }
    }
    

    private void showPopWindow() {
        mPopupWindow.showAsDropDown(this, 0, 5);
        showRiseDrawable();
    }

    private void showDropDrawable() {
        mDrawable = getResources().getDrawable(mDropDrawableResId);
        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], mDrawable, getCompoundDrawables()[3]);
    }

    private void showRiseDrawable() {
        mDrawable = getResources().getDrawable(mRiseDrawableResID);
        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], mDrawable, getCompoundDrawables()[3]);
    }

    public void setListAdapter(BaseAdapter adapter) {
        mPopListView.setAdapter(adapter);
    }

    private void closeSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
    }

    
    public void setOnItemClick(OnItemClickListener onItemClickListener)
    {	
    	mPopListView.setOnItemClickListener(onItemClickListener);
    }
    
    private void setSelectedId(String id)
    {
    	this.selectedId = id;
    }
    
    private void hidePop()
    {
    	if (mPopupWindow.isShowing()) {
    		mPopupWindow.dismiss();
		}
    }
    
    /**   
     * @author: HYM 
     * @Title: doListItemClick   
     * @Description: TODO(执行下拉listview的item被点击事件)   
     * @param: @param text
     * @param: @param id      
     * @return: void       
     * @throws   
     */  
    public void doListItemClick(String text,String id)
    {
    	isShowPop = false;
    	this.setText(text);
    	setSelectedId(id);
    	hidePop();
    }
    
    /**   
     * @author: HYM 
     * @Title: doItemClick   
     * @Description: TODO(执行autotext的下拉点击事件)   
     * @param: @param text
     * @param: @param id      
     * @return: void       
     * @throws   
     */  
    public void doItemClick(String text,String id)
    {
    	isShowPop = false;
    	this.setText(text);
    	setSelectedId(id);
    	dismissDropDown();
    }
    
    @Override
    public boolean enoughToFilter()
    {
    	//判断是否弹出autotext的下拉list，默认弹出，只有在item被点击时不触发弹出
    	if (isShowPop) {
    		return super.enoughToFilter();
		}
    	isShowPop = true;
    	return false;
    }
    
    
    /**   
     * @author: HYM 
     * @Title: showList   
     * @Description: TODO(展示list列表)   
     * @param:       
     * @return: void       
     * @throws   
     */  
    public void showList()
    {
    	closeSoftInput();
        showPopWindow();
        requestFocus();
    }

    @Override
    public void onDismiss() {
        showDropDrawable(); // 当popWindow消失时显示下拉图标
    }

	public String getSelectedId() {
		return selectedId;
	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}
    
	
}